package com.zhiyizhen.callnumber.common;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import java.util.List;

public class AppUtil {

    private static Context mContext;
    private static Handler sMainHandler;

    private AppUtil() {
    }

    public static void init(Context context) {
        if (context == null) {
            throw new NullPointerException("Context is null");
        }
        mContext = context.getApplicationContext();
        ScreenUtil.init(mContext);
    }

    public static synchronized Handler getMainHandler() {
        if (sMainHandler == null) {
            sMainHandler = new Handler(Looper.getMainLooper());
        }
        return sMainHandler;
    }

    public static Context getContext() {
        return mContext;
    }

    public static Object getSystemService(@NonNull String name) {
        return mContext.getSystemService(name);
    }

    public static Resources getResources() {
        return mContext.getResources();
    }

    public static String getPackageName() {
        return mContext.getPackageName();
    }

    /**
     * 获取版本名
     */
    public static String getVersionName() {
        return getVersionName(getPackageName());
    }

    /**
     * 获取版本名
     */
    public static String getVersionName(final String packageName) {
        if (!TextUtils.isEmpty(packageName)) {
            try {
                PackageManager pm = mContext.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(packageName, 0);
                return pi == null ? null : pi.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                LogUtil.e(e);
            }
        }
        return "";
    }

    /**
     * 获取版本号
     */
    public static int getVersionCode() {
        return getVersionCode(getPackageName());
    }

    /**
     * 获取版本号
     */
    public static int getVersionCode(final String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return -1;
        }
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? -1 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            LogUtil.e(e);
        }
        return -1;
    }

    /**
     * 是否为主进程
     */
    public static boolean isMainProcess() {
        android.app.ActivityManager am = ((android.app.ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<android.app.ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (android.app.ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }


    private static String channelName = null;

    /**
     * 获取线上电子市场渠道
     */
    public static String getMarketChannel() {
        if (!TextUtils.isEmpty(channelName)) {
            return channelName;
        }
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA);
            channelName = applicationInfo.metaData.getString("BaiduMobAd_CHANNEL");
        } catch (Exception e) {
            LogUtil.e(e);
            channelName = "official";
        }
        return channelName;
    }

    /**
     * @param mobile 手机号
     * @return 第四位到第七位被星星替代的手机号
     */
    public static String getMaskMobile(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            return null;
        }
        StringBuilder maskMobile = new StringBuilder();
        if (mobile.length() == 11) {
            maskMobile.append(mobile.substring(0, 3))
                    .append("****")
                    .append(mobile.substring(7));
        }

        return maskMobile.toString();
    }

    /**
     * 判断应用是否正在前台运行
     *
     * @param context 上下文
     * @return true：是
     */
    public static boolean isFrontRunning(Context context) {
        android.app.ActivityManager am = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) {
            return false;
        }

        List<android.app.ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        if (runningProcesses == null) {
            return false;
        }
        for (android.app.ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            //前台程序
            if (processInfo.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                final String[] pkgList = processInfo.pkgList;
                if (pkgList == null) {
                    continue;
                }
                for (String activeProcess : pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 字符串转数字
     */
    public static int string2Int(String input) {
        if (TextUtils.isEmpty(input)) {
            return 0;
        }
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException e) {
            LogUtil.e(e);
        }
        return 0;
    }


    /**
     * 将姓名中间的字符替换为*
     * 2个字：返回 X*（如：张三 → 张*）
     * 3个及以上字：返回 X*X（如：张大大 → 张*大）
     * @param name 原始姓名
     * @return 处理后的姓名，若输入为空则返回空
     */
    public static String maskName(String name) {
        // 处理空值或空白字符串
        if (name == null || name.trim().isEmpty()) {
            return name;
        }

        // 去除可能的空格
        name = name.trim();
        int length = name.length();

        // 单个字符直接返回
        if (length == 1) {
            return name;
        }
        // 两个字符，返回第一个字符加*
        else if (length == 2) {
            return name.charAt(0) + "*";
        }
        // 三个及以上字符，保留首尾，中间用*代替
        else {
            char first = name.charAt(0);
            char last = name.charAt(length - 1);
            return first + "*" + last;
        }
    }
}
